package ljl.alg.jianzhioffer.round3.medium;

public class _12_exist {

    public boolean exist(char[][] board, String word) {
        int m = board.length;
        int n = board[0].length;
        boolean[][] visited = new boolean[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == word.charAt(0) && yes(visited, board, i, j, word, 0))
                    return true;
            }
        }
        return false;
    }
    boolean yes(boolean[][] visited, char[][] board, int row, int col, String word, int i) {
        if (row >= board.length || row < 0 || col >= board[0].length || col < 0 || visited[row][col] || board[row][col] != word.charAt(i))
            return false;
        if (i == word.length() - 1)
            return true;
        visited[row][col] = true;
        boolean res = yes(visited, board, row + 1, col, word, i + 1)
                || yes(visited, board, row, col + 1, word, i + 1)
                || yes(visited, board, row - 1, col, word, i + 1)
                || yes(visited, board, row, col - 1, word, i + 1);
        visited[row][col] = false;
        return res;
    }

}
